<!-- 备件管理-备件台账页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common equip-spareParts-ledger">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="种类">
              <px-select v-model="queryParams.category" filterable clearable placeholder="请选择种类" @change="handleCategoryChange">
                <px-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="备件名称/编码">
              <px-input
                v-model="queryParams.spareNameOrCode"
                placeholder="请输入备件名称/编码"
                maxlength="50"
                clearable
                @blur="queryParams.spareNameOrCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6">
            <px-form-item label="类型">
              <px-tree-select
                v-model="queryParams.typeCode"
                placeholder="请选择类型"
                filterable
                clearable
                :data="typeList"
                :render-after-expand="false"
                :props="{ children: 'children', label: 'name', value: 'code' }"
                @visible-change="initTypeList"
                @change="handleTypeChange"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="品牌">
              <px-select
                v-model="queryParams.brandCode"
                filterable
                clearable
                placeholder="请选择品牌"
                @focus="initBrandList"
                @change="handleBrandChange"
              >
                <px-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.code" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="厂商型号">
              <px-select
                v-model="queryParams.supplyModel"
                placeholder="请选择厂商型号"
                filterable
                clearable
                @focus="initSupplyModelList"
                @change="changeSupplyModel"
              >
                <px-option v-for="item in supplyModelList" :key="item.id" :label="item.supplyModel" :value="item.supplyModel" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_ADD'" style="margin-right: 8px" type="primary" @click="addSpareParts">新增</px-button>
        <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_DOWNLOAD_TEMPLATE'" style="margin-right: 8px" type="primary" plain @click="templateDownload"
          >下载模板</px-button
        >
        <BatchUpload
          url="/ifp/digitaltwins/api/v1/sparePartNew/importData"
          permission="ALL_EQUIP_SPAREPARTS_LEDGER_BATCH_UPLOAD"
          @updateUploadPage="queryTable"
        />
        <px-button
          v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_BATCH_DOWNLOAD'"
          style="margin-right: 16px"
          type="primary"
          plain
          :disabled="selectIds.length == 0"
          @click="batchDownload"
          >批量下载</px-button
        >
        <px-checkbox v-model="queryParams.stockAlarm" label="库存预警" @change="queryTable" />
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 346px)" border @selection-change="selectionChange">
        <px-table-column type="selection" width="50" align="center" fixed="left" />
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <px-button
              v-if="item.sparePartName && showRowText('ALL_EQUIP_SPAREPARTS_LEDGER_VIEW')"
              link
              type="primary"
              @click="handleView(scope.row)"
            >
              {{ scope.row.sparePartName }}
            </px-button>
            <span v-else-if="item.sparePartName && !showRowText('ALL_EQUIP_SPAREPARTS_LEDGER_VIEW')">{{ scope.row.sparePartName }}</span>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top" append-to=".equip-spareParts-ledger">
              <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top" append-to=".equip-spareParts-ledger">
              <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="复制" placement="top" append-to=".equip-spareParts-ledger">
              <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_COPY'" link icon="DocumentCopy" type="primary" @click="handleCopy(scope.row)" />
            </px-tooltip>
            <px-tooltip content="备件入库" placement="top" append-to=".equip-spareParts-ledger">
              <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_IN'" link type="primary" @click="handleIn(scope.row)">
                <component :is="markRaw(boxIn)" />
              </px-button>
            </px-tooltip>
            <px-tooltip content="备件出库" placement="top" append-to=".equip-spareParts-ledger">
              <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_OUT'" link type="primary" @click="handleOut(scope.row)">
                <component :is="markRaw(boxOut)" />
              </px-button>
            </px-tooltip>
            <px-tooltip content="删除" placement="top" append-to=".equip-spareParts-ledger">
              <px-button v-has="'ALL_EQUIP_SPAREPARTS_LEDGER_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddSparePartsDetail
      :isMain="isMain"
      :isView="isView"
      :drawerType="drawerType"
      :sparePartsId="sparePartsId"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 详情查看页面 -->
    <ViewSparePartsDetail
      :isMain="isMain"
      :isView="isView"
      :sparePartsId="sparePartsId"
      :sparePartsModelCode="sparePartsModelCode"
      @backMainPage="backMainPage"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_SPAREPARTS_LEDGER"
});
import { queryDictData } from "@/api/common";
import { deleteSparePartsLedgerNew, querySparePartsLedgerNew, queryListTree_1, queryListPage_5, queryBrandList } from "@/api/equip/spareParts";
import boxIn from "@/assets/svg/operation/box_in.svg?component";
import boxOut from "@/assets/svg/operation/box_out.svg?component";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { showRowText } from "@/utils/pengxi";
import { getCurrentInstance, markRaw, onActivated, onMounted, reactive, toRefs } from "vue";
import { useRouter } from "vue-router";
import AddSparePartsDetail from "./components/AddSparePartsDetail.vue";
import ViewSparePartsDetail from "./components/ViewSparePartsDetail.vue";

const router = useRouter();
const { proxy }: any = getCurrentInstance();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  categoryList: [],
  typeList: [],
  brandList: [],
  supplyModelList: [],
  queryParams: {
    category: "",
    spareNameOrCode: "",
    className: "",
    typeCode: "",
    brandCode: "",
    modelCode: "",
    stockAlarm: false, // 库存预警
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "100", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartName", label: "名称", minWidth: "140", showOverflowTooltip: true, sparePartName: true },
    { prop: "sparePartCode", label: "编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "100", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "100", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "100", showOverflowTooltip: true },
    { prop: "supplyModel", label: "厂商型号", minWidth: "100", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "100", showOverflowTooltip: true },
    { prop: "currentStock", label: "库存量", minWidth: "100", showOverflowTooltip: true },
    { prop: "alarmStock", label: "安全库存量", minWidth: "100", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "100", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  selectIds: [],
  downloadParams: {
    ids: [],
    category: "",
    spareNameOrCode: "",
    className: "",
    typeCode: "",
    brandCode: "",
    modelCode: "",
    stockAlarm: false
  },
  drawerType: "add",
  sparePartsId: "",
  sparePartsModelCode: "",
  isFirstLoad: true
});
const {
  isMain,
  isView,
  categoryList,
  typeList,
  brandList,
  supplyModelList,
  queryParams,
  tableColumns,
  tableData,
  total,
  selectIds,
  downloadParams,
  drawerType,
  sparePartsId,
  sparePartsModelCode,
  isFirstLoad
} = toRefs(state);
// 进入页面时触发
onActivated(() => {
  if (!isFirstLoad.value) {
    initCategory();
    queryTable();
  }
});
onMounted(() => {
  initCategory();
  queryTable();
});
// 种类下拉框
const initCategory = async () => {
  const params = { typeCode: "typeCategory" };
  const data = await queryDictData(params);
  categoryList.value = data || [];
};
// 改变种类，清空类型、品牌、厂商型号
const handleCategoryChange = () => {
  typeList.value = [];
  brandList.value = [];
  supplyModelList.value = [];
  queryParams.value.typeCode = "";
  queryParams.value.brandCode = "";
  queryParams.value.modelCode = "";
  queryParams.value.supplyModel = "";
};
// 类型下拉框
const initTypeList = async () => {
  const data = await queryListTree_1({ className: queryParams.value.className });
  typeList.value = data || [];
};
// 改变类型，清空品牌、厂商型号
const handleTypeChange = () => {
  brandList.value = [];
  supplyModelList.value = [];
  queryParams.value.brandCode = "";
  queryParams.value.modelCode = "";
  queryParams.value.supplyModel = "";
};
// 品牌下拉框
const initBrandList = async () => {
  const data = await queryBrandList({ typeCode: queryParams.value.typeCode });
  brandList.value = data || [];
};
// 改变品牌，清空厂商型号
const handleBrandChange = async () => {
  supplyModelList.value = [];
  queryParams.value.modelCode = "";
  queryParams.value.supplyModel = "";
};
// 厂商型号下拉框
const initSupplyModelList = async () => {
  const params = { category: queryParams.value.category, typeCode: queryParams.value.typeCode, brandCode: queryParams.value.brandCode };
  const data = await queryListPage_5(params);
  supplyModelList.value = data?.data || [];
};
// 改变厂商型号, 赋值型号
const changeSupplyModel = async () => {
  const arr = supplyModelList.value.filter(item => {
    return item.supplyModel === queryParams.value.supplyModel;
  });
  if (arr && arr.length > 0) {
    queryParams.value.modelCode = arr[0].code;
  } else {
    queryParams.value.modelCode = "";
  }
};
// 查询备件列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await querySparePartsLedgerNew(params);
  tableData.value = data?.data || [];
  total.value = data?.total;
  downloadParams.value = {
    ids: [],
    category: queryParams.value.category,
    spareNameOrCode: queryParams.value.spareNameOrCode,
    className: queryParams.value.className,
    typeCode: queryParams.value.typeCode,
    brandCode: queryParams.value.brandCode,
    modelCode: queryParams.value.modelCode,
    stockAlarm: queryParams.value.stockAlarm
  };
  isFirstLoad.value = false;
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    category: "",
    spareNameOrCode: "",
    className: "",
    typeCode: "",
    brandCode: "",
    modelCode: "",
    stockAlarm: false,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
// 下载模版
const templateDownload = async () => {
  proxy.download("get", "/digitaltwins/api/v1/sparePartNew/templateDownLoad", {}, "备件台账信息模板.xlsx");
};
// 表格多选框选中
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
};
// 批量下载
const batchDownload = async () => {
  downloadParams.value.ids = selectIds.value;
  const params = downloadParams.value;
  proxy.download("post", "/digitaltwins/api/v1/sparePartNew/exportData", params, "备件台账.xlsx");
};
// 查看备件详情
const handleView = (row: any) => {
  sparePartsId.value = row.id;
  sparePartsModelCode.value = row.modelCode;
  isMain.value = false;
  isView.value = true;
};
// 添加备件详情
const addSpareParts = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
};
// 编辑备件详情
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  sparePartsId.value = row.id;
  isMain.value = false;
  isView.value = false;
};
// 复制
const handleCopy = async row => {
  drawerType.value = "copy";
  sparePartsId.value = row.id;
  isMain.value = false;
  isView.value = false;
};
// 入库
const handleIn = async row => {
  router.push(`/all/equip/spareParts/warehousing?source=ledger&id=${row.sparePartCode}`);
};
// 出库
const handleOut = async row => {
  router.push(`/all/equip/spareParts/outbound?source=ledger&code=${row.sparePartCode}`);
};
// 删除备件
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前备件“${row.sparePartName}”吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteSparePartsLedgerNew({ id: row.id });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  typeList.value = [];
  brandList.value = [];
  supplyModelList.value = [];
  queryParams.value.typeCode = "";
  queryParams.value.brandCode = "";
  queryParams.value.modelCode = "";
  queryParams.value.supplyModel = "";
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
</style>
